package com.cardbaobao.cardbabyclient.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cardbaobao.cardbabyclient.R;
import com.cardbaobao.cardbabyclient.api.Api;
import com.cardbaobao.cardbabyclient.base.BaseResult;
import com.cardbaobao.cardbabyclient.base.Constant;
import com.cardbaobao.cardbabyclient.buried.Self;
import com.cardbaobao.cardbabyclient.ui.activity.base.BaseActivity;
import com.cardbaobao.cardbabyclient.ui.activity.web.AgreementWebViewActivity;
import com.cardbaobao.cardbabyclient.utils.ApplicationHelper;
import com.cardbaobao.cardbabyclient.buried.GoogleAnalyticsUtil;
import com.cardbaobao.cardbabyclient.utils.ImageLoaderUtil;
import com.cardbaobao.cardbabyclient.utils.JsonUtil;
import com.cardbaobao.cardbabyclient.utils.ToastUtil;
import com.cardbaobao.cardbabyclient.utils.URLUtil;
import com.cardbaobao.cardbabyclient.widget.TitleBar;

import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;
import rx.Subscriber;

/**
 * Created by Jiangzx on 2017/9/12 16:01.
 */

public class QuickDebitShowActivity extends BaseActivity {
    public static final String ORDER_NO_S="orderNo";//订单号
    public static final String NAME_S="name";//姓名
    public static final String MOBILE_S="mobile";//手机号码
    public static final String AMOUNT_D="amount";//付款金额

    public static final String CARD_NAME_S="cardName";//信用卡名
    public static final String CARD_TAIL_NUMBER_S="tailNumber";//尾号
    public static final String CARD_LOGO_S="logo";//信用卡logo

    private static final int COUNT_DOWN_TOTAL=60;
    private int countDown;

    @BindView(R.id.title_bar)
    TitleBar titleBar;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone_number)
    TextView tvPhone;
    @BindView(R.id.tv_amount)
    TextView tvAmount;
    @BindView(R.id.ll_verify_code)
    LinearLayout llVerifyCode;
    @BindView(R.id.et_verify_code)
    EditText etVerifyCode;
    @BindView(R.id.bt_send_verify_code)
    Button btSendVerifyCode;
    @BindView(R.id.view_divider_verify_code)
    View divider;
    @BindView(R.id.iv_logo)
    ImageView ivLogo;
    @BindView(R.id.tv_bank)
    TextView tvBank;
    @BindView(R.id.tv_card)
    TextView tvCard;

    @BindView(R.id.bt_ensure_commit)
    Button btEnsure;

    String orderNo;
    String mobile;
    private Handler handler;
    @Override
    protected int getLayoutId() {
        return R.layout.activity_quick_debit_show;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        titleBar.setLeftViewOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        Intent intent = getIntent();

        mCurrentPageId= Self.Page.app_quick_receivables_phone_verification;

        orderNo = intent.getStringExtra(ORDER_NO_S);
        String name = intent.getStringExtra(NAME_S);
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = name.length(); i < length; i++) {
            if (i == length - 1) {
                sb.append(name.substring(i, i + 1));
            } else {
                sb.append("*");
            }
        }
        tvName.setText(sb.toString());

        mobile = intent.getStringExtra(MOBILE_S);
        tvPhone.setText(mobile.substring(0, 3) + "*****" + mobile.substring(8));
        tvAmount.setText(String.format(Locale.CHINESE, "%.2f", intent.getDoubleExtra(AMOUNT_D, 0.0D)) + "元");
        ImageLoaderUtil.displayImage(URLUtil.CBB_IMG_URL + intent.getStringExtra(CARD_LOGO_S),
                ivLogo);
        tvBank.setText(intent.getStringExtra(CARD_NAME_S));
        tvCard.setText("信用卡尾号" + intent.getStringExtra(CARD_TAIL_NUMBER_S));

        handler = new Handler();
        sendDebitSms(String.valueOf(mApplication.getUser().getID()), orderNo);
    }

    @Override
    protected void onResume() {
        super.onResume();
        GoogleAnalyticsUtil.setScreenName("快捷收款确认");
    }

    Runnable runnable=new Runnable() {
        @Override
        public void run() {
            if(countDown>0){
                countDown--;
                btSendVerifyCode.setText(countDown+"s后重发");
                handler.postDelayed(this,Constant.ONE_SECOND);
            }else{
                btSendVerifyCode.setEnabled(true);
                btSendVerifyCode.setText("发送验证码");
            }
        }
    };

    private void startCountDown(){
        countDown=COUNT_DOWN_TOTAL;
        handler.postDelayed(runnable,Constant.ONE_SECOND);
    }

    private void sendDebitSms(String userId,String orderNo){
        showProgressDialog(false);
        Api.quickDebitSms(userId,orderNo).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_data_fail));
                btSendVerifyCode.setEnabled(true);
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                BaseResult result= JsonUtil.json2Object(s,BaseResult.class);
                if(result.getCode()== Constant.SUC_CODE){
                    //发送短信成功，开始倒计时
                    startCountDown();
                }else{
                    ToastUtil.showToast(result.getMsg());
                    btSendVerifyCode.setEnabled(true);
                }
            }
        });
    }

    //付款
    private void quickDebitEnsure(String verifyCode){
        showProgressDialog(false);
        Api.quickDebitEnsure(String.valueOf(mApplication.getUser().getID()),
                orderNo,verifyCode).subscribe(new Subscriber<String>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable throwable) {
                dismissProgressDialog();
                ToastUtil.showToast(ApplicationHelper.getApplicationContext().
                        getString(R.string.string_request_server_fail));
            }

            @Override
            public void onNext(String s) {
                dismissProgressDialog();
                BaseResult result=JsonUtil.json2Object(s,BaseResult.class);
                Intent intent=new Intent(QuickDebitShowActivity.this,
                            QuickDebitResultActivity.class);
                intent.putExtra(QuickDebitResultActivity.DEBIT_RESULT_CODE_I,
                        result.getCode());
                intent.putExtra(ORDER_NO_S,orderNo);
                intent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(intent);
                finish();
            }
        });
    }

    @OnTextChanged(R.id.et_verify_code)
    public void afterTextChange(Editable s){
        if(s.length()>0){
            btEnsure.setEnabled(true);
        }else{
            btEnsure.setEnabled(false);
        }
    }

    @OnClick({R.id.bt_send_verify_code,R.id.tv_agreement,R.id.bt_ensure_commit})
    public void onClick(View view){
        switch (view.getId()){
            case R.id.bt_send_verify_code:
                //发送验证码
                btSendVerifyCode.setEnabled(false);
                sendDebitSms(String.valueOf(mApplication.getUser().getID()),orderNo);
                break;
            case R.id.tv_agreement:
                //收款服务协议
                Intent agreementIntent=new Intent(this, AgreementWebViewActivity.class);
                agreementIntent.putExtra(AgreementWebViewActivity.WEB_TITLE_S,
                        "收款服务协议");
                agreementIntent.putExtra(AgreementWebViewActivity.WEB_URL_S,
                        URLUtil.QUICK_DEBIT_AGREEMENT);
                agreementIntent.putExtra(AgreementWebViewActivity.WEB_TYPE_I,10);
                agreementIntent.putExtra(PRE_PAGE_ID_S,mCurrentPageId);
                startActivity(agreementIntent);
                break;
            case R.id.bt_ensure_commit:
                //确定支付
                quickDebitEnsure(etVerifyCode.getText().toString().trim());
                break;
        }
    }
}
